from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from course import models,courseser

# Create your views here.
class HomeCate(APIView):
    def get(self,request):
        #有效的一级分类并且按照sort字段排序
        data=models.Category.objects.filter(isdel=False,parent=None).order_by("sort")
        ser=courseser. CategorySerializer(data,many=True)
        alldata=ser.data
        for item in alldata:
            item["children"]=item["children"][:3]#只取前三个
        return Response({"msg":"ok","data":ser.data})

from django.core.cache import cache
#设置缓存 catch.set(key,value,timeout)  value可以是字符串，字典，列表
#读取缓存 catch.get(key)
#删除缓存 catch.delete(key)
class TestCate(APIView):
    def get(self,request):
        # data = models.Category.objects.filter(isdel=False, parent=None).order_by("sort")
        # ser=courseser.CateSerializer(data,many=True)
        cache.set("code","123456",60*2)
        cache.set("stu",["张三","lisi","王五"],60*2)
        cache.set("stu1",{"name":"张三","age":18},60*2)
        return Response({"msg":"ok","code":cache.get("code"),"stu":cache.get("stu"),"stu1":cache.get("stu1")})


class HomeChild(APIView):
    def get(self,request):
        #先获取一级分类id
        parent=request.query_params.get("parent")
        if not parent:
            return Response({"msg":"一级分类id不能为空","code":400})
        #根据一级分类id获取二级分类
        info=models.Category.objects.filter(isdel=False,id=parent).first()
        ser=courseser.CategorySerializer(info)
        return Response({"msg":"ok","data":ser.data})

#分类列表页 方向的展示
class  OneCate(APIView):
    def get(self,request):
        #1 获取一级分类的有效数据按照sort排序
        data = models.Category.objects.filter(isdel=False, parent=None).order_by("sort")
        #2 序列化
        ser=courseser.CategorySer(data,many=True)
        #3 返回
        return Response({"msg":"ok","data":ser.data,"code":200})
#分类列表页 二级分类展示
class  TwoCate(APIView):
    def get(self,request):
        #1 获取到一级分类的id
        direction=request.query_params.get("direction","0")
        #2 如果一级分类等于 0 获取到所有的二级分类 不等于0 获取自己的分类
        if direction=="0":
            data = models.Category.objects.filter(isdel=False, parent__isnull=False).order_by("sort")
        else:
            data = models.Category.objects.filter(isdel=False, parent=direction).order_by("sort")
        #3 序列化
        ser = courseser.CategorySer(data, many=True)
        #4 返回
        return Response({"msg":"ok","data":ser.data,"code":200})